package com.itogis.util;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.wabacus.config.Config;

/**
 * 过滤器
 * @author Administrator
 *
 */
public class RequestFilter implements Filter
{
    private FilterConfig filterConfig = null;

    public void init(FilterConfig filterConfig) throws ServletException
    {

        this.filterConfig = filterConfig;
    }
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain)
    {
        try
        {
        	HttpServletRequest httpRequest=(HttpServletRequest)request;
        	HttpServletResponse httpResponse=(HttpServletResponse)response; 
            if(!Config.encode.equalsIgnoreCase("utf-8"))
            {//如果当前项目采用的不是UTF-8编码
                
                String contentType=httpRequest.getContentType();
                if (contentType != null
                        && contentType.toLowerCase().startsWith(
                                "application/x-www-form-urlencoded; charset=utf-8"))
                {//报表提交
                    request.setCharacterEncoding("UTF-8");
                }else
                {
                    request.setCharacterEncoding(Config.encode);
                }
                response.setContentType("text/html; charset="+Config.encode);
            }else
            {
                request.setCharacterEncoding("UTF-8");
                response.setContentType("text/html;charset=UTF-8");
            }
            /**
             * 如果session失效，则返回登录界面
             */
            HttpSession  session = httpRequest.getSession(false);
            if(session!=null&&session.getAttribute("userInfoBean")!=null){
            	chain.doFilter(request,response);
            }else{
            	if(httpRequest.getRequestURI().indexOf("/rest/login")>-1
            			||httpRequest.getRequestURI().indexOf("/index.html")>-1){
            		chain.doFilter(request,response);
            	}else{
            		httpResponse.sendRedirect(httpRequest.getContextPath()+"/index.html");
            	}
            }
        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }
    public void destroy()
    {
        this.filterConfig = null;
    }
}